<?php

namespace app\api\model;

use app\api\model\Goods\Speci\Brand;
use app\api\model\Goods\Speci\Category;
use app\api\model\Goods\Speci\Material;
use app\api\model\Goods\Speci\Season;
use app\api\model\Goods\Speci\Unit;
use app\api\model\Goods\Speci\Color;
use app\api\model\Goods\Speci\Size;
use app\api\model\Goods\Speci\Style;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;
use think\Db;

/**
 * Class Commodity
 * @package app\api\model
 */
class Commodity extends Model
{
    protected $table = 'jxc_commodity';

    public function getSeasonAttr($value)
    {
        return Season::field('id,name as season_name')->find($value);
        //return Season::find($value)['name'];
    }

    public function getMaterialAttr($value)
    {
        return Material::field('id,name as material_name')->find($value);
        //return Material::find($value)['name'];
    }

    public function getUnitAttr($value)
    {
        return Unit::field('id,name as unit_name')->find($value);
        //return Unit::find($value)['name'];
    }

    public function getCategoryAttr($value)
    {
        return Category::field('id,name as cate_name')->find($value);
        //return Category::find($value)['name'];
    }

    public function getBrandAttr($value)
    {
        return Brand::field('id,name as brand_name')->find($value);
        //return Brand::find($value)['name'];
    }

    public function getImagesAttr($value)
    {
        if (is_null($value)) {
            return json_encode(['http://iph.href.lu/200x200?text=%E6%9A%82%E6%97%A0%E5%9B%BE%E7%89%87']);
        } else {
            return $value;
        }
    }

    /**
     * @return \think\model\relation\HasMany
     */
    public function products()
    {
        return $this->hasMany(Product::class, 'commodity_id');
    }

    public function shops()
    {
        return $this->hasMany(ShopModel::class, 'commodity_id');
    }

    public function getField()
    {
        $commodity = self::getTableFields();
        $product = self::getTableFields('jxc_product');
        // 单品表 商品表共有字段
        $org = array_diff($commodity, $product);
        // 单品表的私有字段
        //$arr['product'] = array_diff($product, $org);
        // 商品表的私有字段
        //$arr['commodity'] = array_diff($commodity, $org);
        return ['product' => self::getTableFields('jxc_product'), 'commodity' => self::getTableFields(), 'org' => $org];
//        return array_diff(self::getTableFields('jxc_product'), // TODO:: 其他字段
//            array_diff(self::getTableFields('jxc_goods'), // TODO:: 单品表的私有字段
//                array_diff(self::getTableFields(), ["remarks","sort", "status", "create_time"])// TODO:: 商品表的私有字段
//            )
//        );
    }

    /**
     * @param $data
     * @param int $page
     * @param int $size
     * @param string $with
     * @return string|\think\Paginator
     */
    public function index($data, $page = 1, $size = 10, $with = 'products')
    {
        try {
            $list = self::with($with)->where($data)->page($page, $size)->order('id desc')->paginate($size);
            $list = $list->each(function ($comm) {
                $comm['images'] = json_decode($comm['images'], true);
                return $comm;
            });
            return $list;
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model|null
     */
    public function info($id)
    {
        try {
            $list = self::with('products')->findOrFail($id);
            $list['images'] = json_decode($list['images'], true);
            $list->products->each(function ($v) {
                $v['color_id'] = (int)$v->getData()['color'];
                $v['size_id'] = (int)$v->getData('size');
                $v['style_id'] = (int)$v->getData('style');
                return $v;
            });
            return $list;
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getGoods($where, $page = 1, $size = 10)
    {
        try {
            $commodity = self::where($where)->order('id desc')->select()->toArray();
            $list = array_map(function ($c) {
                $product = Product::where('commodity_id', $c['id'])->field('id as product_id,color,size')
                    ->fetchCollection()->select();
                $c['product'] = $product->map(function ($p) {
                    $spec = [];
                    if (isset($spec['color']) && ($p['color'] === $spec['color'])) {
                        $spec['list'][] = $p;
                    } else {
                        $spec['color'] = $p['color'];
                        $spec['list'][] = $p;
                    }
                    if (isset($spec['size']) && ($p['size'] === $spec['size'])) {
//                        $spec['list'][] = $p;
                    } else {
                        $spec['size'] = $p['size'];
//                        $spec['list'][] = $p;
                    }
                    $p = $spec;
                    return $p;
                });
                return $c;
            }, $commodity);
            return $list;
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param array $data
     * @return Commodity
     */
    public function add(array $data)
    {
        $data['create_time'] = time();
        if (isset($data['images'])) {
            $data['images'] = array_map(function ($v) {
                return parse_url($v)['path'];
            }, $data['images']);
            $data['images'] = json_encode($data['images'], 256);
        }
        return self::create($data);
    }

    /**
     * @param int $id
     * @param array $data
     * @return int|string
     */
    public function edit(int $id, array $data)
    {
        try {
            if (isset($data['images'])) {
                $data['images'] = array_map(function ($v) {
                    return parse_url($v)['path'];
                }, $data['images']);
                $data['images'] = json_encode($data['images'], 256);
            }
            return self::where(['id' => $id])->update($data);
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param int $id
     * @param bool $recursive
     * @return int
     */
    public function del(int $id, bool $recursive = false)
    {
        try {
            $product = self::getOrFail($id)->products();
            if ($product->count()) {
                // 传入递归标识 则删除商品和单品
                if ($recursive) {
                    $res['product'] = $product->delete();
                    return $res['commodity'] = self::where('id', $id)->delete();
                }
                return '还有关联的单品未删除';
            }
            return self::where('id', $id)->delete();
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}
